package org.example.threadpool;

import org.apache.commons.lang3.ArrayUtils;
import org.example.bio.TimeServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <p> 时间服务器 </p>
 *
 * @author Chris
 * @since 2024/3/23 13:16
 */
public class TimeServer {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(TimeServer.class);

    public static void main(String[] args) {
        int port = 8080;

        if (ArrayUtils.isNotEmpty(args)) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                log.error("error=", e);
            }
        }

        try (final ServerSocket serverSocket = new ServerSocket(port)) {
            log.info("The time serve is start in port : " + port);

            TimeServerHandlerExecutePool threadPool = new TimeServerHandlerExecutePool(50, 10000);
            while (true) {
                final Socket socket = serverSocket.accept();
                threadPool.execute(new TimeServerHandler(socket));
            }
        } catch (IOException e) {
            log.error("error=", e);
        } finally {
            log.info("The time server close");
        }
    }
}